package com.ttg.web.dao.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ttg.common.entities.BasePage;
import com.ttg.common.exception.BaseException;
import com.ttg.model.dto.QMReportDTO;
import com.ttg.model.mapper.QualityManageMerchReportMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ttg.model.pojo.QualityManageMerchReport;
import com.ttg.model.pojo.QualityManageIndustryReport;
import com.ttg.model.pojo.QualityManageMerchReport;
import com.ttg.model.vo.QMMerchReportVO;
import com.ttg.web.dao.QualityManageMerchReportDao;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (TblQualityManageMerchReport) daoImpl
 *
 * @author chenyou
 * @datetime 2025-08-18 14:50:36
 */
@Service
public class QualityManageMerchReportDaoImpl extends ServiceImpl<QualityManageMerchReportMapper, QualityManageMerchReport> implements QualityManageMerchReportDao {

    @Override
    public QualityManageMerchReport getByUnique(String year,String month, String mctNo) {
        LambdaQueryWrapper<QualityManageMerchReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QualityManageMerchReport::getRepYear,year)
                .eq(QualityManageMerchReport::getRepMonth,month)
                .eq(QualityManageMerchReport::getRepMctNo,mctNo);
        return getOne(wrapper);
    }

    @Override
    public List<String> getMctNoList(String year, String month) {
        LambdaQueryWrapper<QualityManageMerchReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QualityManageMerchReport::getRepYear,year)
                .eq(QualityManageMerchReport::getRepMonth,month);
        wrapper.select(QualityManageMerchReport::getRepMctNo);
        List<QualityManageMerchReport> list = list(wrapper);
        return list.stream().map(o -> o.getRepMctNo()).collect(Collectors.toList());
    }

    @Override
    public boolean deleteByMonth(String year, String month) {
        LambdaQueryWrapper<QualityManageMerchReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QualityManageMerchReport::getRepYear,year)
                .eq(QualityManageMerchReport::getRepMonth,month);
        return remove(wrapper);
    }

    @Override
    public void deleteByMonthAndMctNos(String year, String month, List<String> mctNos) {
        baseMapper.deleteByMonthAndMctNos(year,month,mctNos);
    }

    @Override
    public void efficientBatchSaveOrUpdate(List<QualityManageMerchReport> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        if(list.size()>1000){
            throw new BaseException("批次更新数量不能超过1000");
        }
        // 1. 查询已存在的记录
        List<QualityManageMerchReport> existRecords = baseMapper.selectExistByMultiFields(list);
        Map<String, QualityManageMerchReport> existRecordMap = existRecords.stream()
                .collect(Collectors.toMap(
                        record -> buildUniqueKey(record.getRepYear(),record.getRepMonth(),record.getRepMctNo()),
                        Function.identity()
                ));

        // 2. 分离需要插入和更新的数据
        List<QualityManageMerchReport> toInsert = new ArrayList<>();
        List<QualityManageMerchReport> toUpdate = new ArrayList<>();

        for (QualityManageMerchReport record : list) {
            String uniqueKey = buildUniqueKey(record.getRepYear(),record.getRepMonth(),record.getRepMctNo());
            QualityManageMerchReport existRecord = existRecordMap.get(uniqueKey);

            if (existRecord != null) {
                // 设置ID用于更新
                record.setRepId(existRecord.getRepId());
                toUpdate.add(record);
            } else {
                toInsert.add(record);
            }
        }

        // 3. 批量操作
        if (!toInsert.isEmpty()) {
            this.saveBatch(toInsert);
        }
        if (!toUpdate.isEmpty()) {
            this.updateBatchById(toUpdate);
        }
    }

    private String buildUniqueKey(String year,String month, String mctNo) {
        return year + "_" + month + "_" + mctNo;
    }

    @Override
    public BasePage<QMMerchReportVO> report(BasePage page, QMReportDTO reqDto) {
        return baseMapper.report(page,reqDto);
    }

    @Override
    public List<String> selectYears() {
        return baseMapper.selectYears();
    }

    @Override
    public List<String> selectMonths(String year) {
        return baseMapper.selectMonths(year);
    }
}

